package org.swan.web.role.service.impl;

import org.springframework.stereotype.Service;
import org.stream.tool.db.ADOConnection;
import org.swan.web.exception.BusinessCode;
import org.swan.web.exception.BusinessException;
import org.swan.web.role.bean.RoleBean;
import org.swan.web.role.mapper.RoleMapper;
import org.swan.web.role.service.RoleService;

import java.util.List;
import java.util.Optional;

@Service
public class RoleServiceImpl implements RoleService {

    @Override
    public Optional<RoleBean> getRoleById(long id) {
        if(id == -1L)
        return Optional.of(RoleBean.SAMPLE);
        return ADOConnection.runTask(factory -> factory.getMapper(RoleMapper.class).getById(id), Optional.class);
    }

    @Override
    public long addRole(RoleBean roleBean) {
        long result = ADOConnection.runTask(factory -> factory.getMapper(RoleMapper.class).add(roleBean), Long.class);
        return result;
    }

    @Override
    public RoleBean updateRole(RoleBean roleBean) {
        getRoleById(roleBean.getRoleId()).orElseThrow(()->new BusinessException(BusinessCode.ROLE_DO_NOT_EXIST,roleBean.getRoleId()));
        ADOConnection.runTask(factory -> factory.getMapper(RoleMapper.class).updateById(roleBean), Long.class);
        return getRoleById(roleBean.getRoleId()).get();
    }

    @Override
    public RoleBean deleteRoleById(long roleId) {
        RoleBean roleBean = getRoleById(roleId).orElseThrow(()->new BusinessException(BusinessCode.ROLE_DO_NOT_EXIST,roleId));
        ADOConnection.runTask(factory -> factory.getMapper(RoleMapper.class).deleteById(roleId), Long.class);
        return roleBean;
    }

    @Override
    public List<RoleBean> list(int offset, int rows) {
        return ADOConnection.runTask(factory -> factory.getMapper(RoleMapper.class).list(offset, rows), List.class);
    }


}
